import { uploadMinio } from '@/services/common';
import request from '@/utils/request';
import { PlusOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { Button, Card, Form, Input, message, Upload } from 'antd';
import React, { useEffect, useState } from 'react';
import styles from './index.less';

interface CompanyInfo {
  companyId: string;
  companyName: string;
  address: string;
  mobile: string;
  email: string;
  longitude: string;
  latitude: string;
  wxQrCode?: string;
  sphQrCode?: string;
  xhsQrCode?: string;
}

const CompanyPage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [editing, setEditing] = useState(false);
  const [companyInfo, setCompanyInfo] = useState<CompanyInfo | null>(null);
  const [wxQrCodeUrl, setWxQrCodeUrl] = useState<string>('');
  const [sphQrCodeUrl, setSphQrCodeUrl] = useState<string>('');
  const [xhsQrCodeUrl, setXhsQrCodeUrl] = useState<string>('');

  // 获取公司详情
  const fetchCompanyDetail = async () => {
    setLoading(true);
    try {
      const response = await request('/company/qryCompanyInfoDetail', {
        method: 'POST',
        data: {},
      });

      if (response.code === '0000') {
        setCompanyInfo(response.data);
        form.setFieldsValue(response.data);
        setWxQrCodeUrl(response.data.wxQrCode || '');
        setSphQrCodeUrl(response.data.sphQrCode || '');
        setXhsQrCodeUrl(response.data.xhsQrCode || '');
      } else {
        message.error(response.msg || '获取公司详情失败');
      }
    } catch (error) {
      console.error('获取公司详情出错:', error);
      message.error('获取公司详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载数据
  useEffect(() => {
    fetchCompanyDetail();
  }, []);

  // 图片上传前的校验
  const beforeUpload = (file: File) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件!');
    }

    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过2MB!');
    }

    return isImage && isLt2M;
  };

  // 创建上传配置函数
  const createUploadProps = (
    fieldName: 'wxQrCode' | 'sphQrCode' | 'xhsQrCode',
    setUrl: (url: string) => void,
  ): UploadProps => ({
    name: 'file',
    customRequest: async ({ file, onSuccess, onError }) => {
      try {
        const response = await uploadMinio(file as File);
        if (response.data?.fileUrl) {
          const url = response.data.fileUrl;
          setUrl(url);
          form.setFieldValue(fieldName, url);
          onSuccess?.(response, new XMLHttpRequest());
          message.success('图片上传成功');
        } else {
          onError?.(new Error('上传失败'), new XMLHttpRequest());
        }
      } catch (error) {
        onError?.(error as Error, new XMLHttpRequest());
        message.error('图片上传失败');
      }
    },
    showUploadList: false,
    beforeUpload,
    onChange(info) {
      if (info.file.status === 'error') {
        message.error('图片上传失败');
      }
    },
  });

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const submitData = {
        ...values,
        wxQrCode: wxQrCodeUrl || values.wxQrCode,
        sphQrCode: sphQrCodeUrl || values.sphQrCode,
        xhsQrCode: xhsQrCodeUrl || values.xhsQrCode,
      };
      const response = await request('/company/updateCompanyInfo', {
        method: 'POST',
        data: submitData,
      });

      if (response.code === '0000') {
        message.success('更新公司信息成功');
        setEditing(false);
        fetchCompanyDetail();
      } else {
        message.error(response.msg || '更新公司信息失败');
      }
    } catch (error) {
      console.error('提交表单出错:', error);
    }
  };

  return (
    <div className={styles.container}>
      <Card
        title="公司信息管理"
        bordered={false}
        loading={loading}
        extra={
          !editing && (
            <Button type="primary" onClick={() => setEditing(true)}>
              编辑
            </Button>
          )
        }
      >
        {companyInfo && (
          <Form form={form} layout="vertical">
            <Form.Item
              name="companyName"
              label="公司名称"
              rules={[{ required: true, message: '请输入公司名称' }]}
            >
              <Input placeholder="请输入公司名称" disabled={!editing} />
            </Form.Item>

            <Form.Item
              name="address"
              label="公司地址"
              rules={[{ required: true, message: '请输入公司地址' }]}
            >
              <Input placeholder="请输入公司地址" disabled={!editing} />
            </Form.Item>

            <Form.Item
              name="mobile"
              label="联系电话"
              rules={[{ required: true, message: '请输入联系电话' }]}
            >
              <Input placeholder="请输入联系电话" disabled={!editing} />
            </Form.Item>

            <Form.Item
              name="email"
              label="邮箱"
              rules={[{ type: 'email', message: '请输入有效的邮箱地址' }]}
            >
              <Input placeholder="请输入邮箱" disabled={!editing} />
            </Form.Item>

            <Form.Item name="longitude" label="经度">
              <Input placeholder="请输入经度" disabled={!editing} />
            </Form.Item>

            <Form.Item name="latitude" label="纬度">
              <Input placeholder="请输入纬度" disabled={!editing} />
            </Form.Item>

            <Form.Item name="wxQrCode" label="微信二维码">
              <Upload {...createUploadProps('wxQrCode', setWxQrCodeUrl)}>
                <div
                  style={{
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                  }}
                >
                  {wxQrCodeUrl ? (
                    <img
                      src={wxQrCodeUrl}
                      alt="微信二维码"
                      style={{
                        width: '100%',
                        maxHeight: '200px',
                        marginBottom: '8px',
                      }}
                    />
                  ) : null}
                  <Button icon={<PlusOutlined />} disabled={!editing}>
                    点击上传
                  </Button>
                </div>
              </Upload>
            </Form.Item>

            <Form.Item name="sphQrCode" label="视频号二维码">
              <Upload {...createUploadProps('sphQrCode', setSphQrCodeUrl)}>
                <div
                  style={{
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                  }}
                >
                  {sphQrCodeUrl ? (
                    <img
                      src={sphQrCodeUrl}
                      alt="视频号二维码"
                      style={{
                        width: '100%',
                        maxHeight: '200px',
                        marginBottom: '8px',
                      }}
                    />
                  ) : null}
                  <Button icon={<PlusOutlined />} disabled={!editing}>
                    点击上传
                  </Button>
                </div>
              </Upload>
            </Form.Item>

            <Form.Item name="xhsQrCode" label="小红书二维码">
              <Upload {...createUploadProps('xhsQrCode', setXhsQrCodeUrl)}>
                <div
                  style={{
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                  }}
                >
                  {xhsQrCodeUrl ? (
                    <img
                      src={xhsQrCodeUrl}
                      alt="小红书二维码"
                      style={{
                        width: '100%',
                        maxHeight: '200px',
                        marginBottom: '8px',
                      }}
                    />
                  ) : null}
                  <Button icon={<PlusOutlined />} disabled={!editing}>
                    点击上传
                  </Button>
                </div>
              </Upload>
            </Form.Item>

            {editing && (
              <div style={{ textAlign: 'right' }}>
                <Button
                  style={{ marginRight: 8 }}
                  onClick={() => {
                    form.resetFields();
                    if (companyInfo) {
                      form.setFieldsValue(companyInfo);
                      setWxQrCodeUrl(companyInfo.wxQrCode || '');
                      setSphQrCodeUrl(companyInfo.sphQrCode || '');
                      setXhsQrCodeUrl(companyInfo.xhsQrCode || '');
                    }
                    setEditing(false);
                  }}
                >
                  取消
                </Button>
                <Button type="primary" onClick={handleSubmit}>
                  保存
                </Button>
              </div>
            )}
          </Form>
        )}
      </Card>
    </div>
  );
};

export default CompanyPage;
